package com.effvi.taoke.utils;

import java.io.IOException;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

public class HttpCommon {

//	private static final Logger log = LoggerFactory.getLogger(HttpCommon.class);
	public static String defaultCookies = "";
	
	private static ThreadSafeClientConnManager cm = null;
	
	private static HttpClient client = null;  
	/**
	 * 初始化连接池
	 */
	static 
	{
		SchemeRegistry schemeRegistry = new SchemeRegistry();
		schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
				.getSocketFactory()));
		schemeRegistry.register(new Scheme("https", 443, SSLSocketFactory
				.getSocketFactory()));
		cm = new ThreadSafeClientConnManager(schemeRegistry);
		try 
		{
			cm.setMaxTotal(200);
		} 
		catch (NumberFormatException e) 
		{
//			log.error("Key[httpclient.max_total] Not Found in systemConfig.properties", e);
			System.out.println("Key[httpclient.max_total] Not Found in systemConfig.properties"+ e);
		}
		// 每条通道的并发连接数设置（连接池）
		try 
		{
			int defaultMaxConnection = 50;// Integer.valueOf(ResourceUtil.getSystem("httpclient.default_max_connection"));
			cm.setDefaultMaxPerRoute(defaultMaxConnection);
		} 
		catch (NumberFormatException e) 
		{
//			log.error("Key[httpclient.default_max_connection] Not Found in systemConfig.properties", e);
			System.out.println("Key[httpclient.default_max_connection] Not Found in systemConfig.properties"+ e);
		}
		
		HttpParams params = new BasicHttpParams();
		params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
		params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // 3000ms
		params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000); // 5000ms
		//实例化一个httpclient
		client = new DefaultHttpClient(cm, params);
	}
	
	
	
	public static String get(String url,String cookies) throws IOException{
		return get(url,cookies,"utf-8");
	}
	
	public static String get(String url,String cookies,String encode) throws IOException{
		HttpGet get=new HttpGet(url);
		try {
			get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
			if(cookies != null && !"".equals(cookies)){
				get.addHeader("Cookie", cookies);
			}
			HttpResponse response = client.execute(get);
			get = null;
			HttpEntity entity = response.getEntity();
			Header[] headers = response.getHeaders("Content-Encoding");
			if(headers != null && headers.length > 0){
				if("gzip".equals(headers[0].getValue())){
					return EntityUtils.toString(new GzipDecompressingEntity(entity), encode);
				}
			}
			return EntityUtils.toString(entity, encode);
		} catch (IOException e) {
			get.abort();
			throw e;
		}catch (Exception e) {
			get.abort();
//			log.error("得到 httpclient 出错",e);
			throw new RuntimeException(e);
		}
	}
}
